import $http from '@/api/index';

const state = {
  user: {
    id: "",
    phoneNum: "",
    username: "",
    token: "",
    name: "用户"
  },
  showLogin: false
};
const getters = {
  isLogin: state => {
    return !(!(state.user.id));
  },
  user: state => state.user,
  showLogin: state => state.showLogin,
};
const actions = {
  logout({
           state,
           getters,
           commit
         }) {
    sessionStorage.clear();
    document.cookie = "";
    commit('set_user', {});
  },
  refreshToken({state, getters, commit}, payload) {
    return new Promise((resolve, reject) => {
      $http.get("/auth/token/refresh").then(res => {
        sessionStorage.hbjwtauth = res.jwtToken;
        commit('set_token', res.jwtToken);
        resolve(res);
      }).catch(err => {
        reject(err);
      });
    });
  },
};
const mutations = {
  set_user: (state, payload) => {
    state.user = payload;
  },
  set_token: (state, payload) => {
    state.user.token = payload;
  },
  showLogin: (state, payload) => {
    state.showLogin = true;
  },
  restore_user_info(state, payload) {
    //从sessionStorage尝试恢复用户数据
    let sessionToken = sessionStorage.getItem("hbjwtauth");
    let sessionUser = sessionStorage.getItem("user");
    if (sessionToken && sessionUser) {
      state.user = JSON.parse(sessionUser);
      state.hbjwtauth = sessionToken;
    }
  }
};

export default {
  state,
  getters,
  actions,
  mutations,
};
